package top.leyi.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


public class EncryptAndDecrypt {

  static final Base64.Encoder encoder = Base64.getEncoder();
  static final Base64.Decoder decoder = Base64.getDecoder();
  
	
  public static void main(String[] args) {
	 // base64Encrypt();
	 try{
		 EncryptAndDecrypt encryptAndDecrypt = new EncryptAndDecrypt();
		 String enmsg =  encryptAndDecrypt.RASEncrypt("057612");
		 String demsg = encryptAndDecrypt.RASDecrypt(enmsg);
         System.out.println("加密后-----------:  "+enmsg);
         System.out.println("解密后-----------:  "+demsg);
         System.out.println(encryptAndDecrypt.MD5Encrypt("057612"));
	 }catch (Exception e) {
		// TODO: handle exception
		 e.printStackTrace();
	}
  }
  
   static void RAS()throws NoSuchAlgorithmException{
	   /*创建非对称加密的公钥和私钥示例 将生成的公钥和私钥用Base64编码后打印出来*/
		  KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
		  keyPairGenerator.initialize(2048); //一般加密位数为1024 对安全要求较高的情况下可以使用2048
		  KeyPair keyPair = keyPairGenerator.generateKeyPair();
		  RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		  RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
	
		  
		  try{
			  Cipher cipher = Cipher.getInstance("RSA");
			  String msg="不破楼兰终不还";
			  cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			  String enmsg = encoder.encodeToString(cipher.doFinal(msg.getBytes()));
			  
			  System.out.println("enmsg:" + enmsg);
			  
			  Cipher cipher2 = Cipher.getInstance("RSA");
			  cipher2.init(Cipher.DECRYPT_MODE, privateKey);
			  
			  String demsg = new String(cipher2.doFinal(decoder.decode(enmsg)), "UTF-8");
			  System.out.println();
			  System.out.println("demsg:" + demsg);
			  
		  }catch(Exception  e){
			  e.printStackTrace();
		  }
   }
   
   static PublicKey getRasPublicKey(){
	   
		  Base64.Decoder decoder = Base64.getDecoder();
		  PublicKey   publicKey = null;
	      String pubKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVRiDkEKXy/KBTe+UmkA+feq1zGWIgBxkgbz7aBJGb5+eMKKoiDRoEHzlGndwFKm4mQWNftuMOfNcogzYpGKSEfC7sqfBPDHsGPZixMWzL3J10zkMTWo6MDIXKKqMG1Pgeq1wENfJjcYSU/enYSZkg3rFTOaBSFId+rrPjPo7Y4wIDAQAB";
	      X509EncodedKeySpec bobPubKeySpec  = new X509EncodedKeySpec(decoder.decode(pubKey));
	   try{
		   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		   publicKey = keyFactory.generatePublic(bobPubKeySpec);
		   
	   }catch(NoSuchAlgorithmException e){
		   e.printStackTrace();
	   } catch (InvalidKeySpecException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	    return publicKey;
   }
   
   static PrivateKey  getRasPrivateKey(){
	   Base64.Decoder decoder = Base64.getDecoder();
	   PrivateKey   privateKey = null;
	   String priKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJVGIOQQpfL8oFN75SaQD596rXMZYiAHGSBvPtoEkZvn54woqiINGgQfOUad3AUqbiZBY1+24w581yiDNikYpIR8Luyp8E8MewY9mLExbMvcnXTOQxNajowMhcoqowbU+B6rXAQ18mNxhJT96dhJmSDesVM5oFIUh36us+M+jtjjAgMBAAECgYABtnxKIabF0wBD9Pf8KUsEmXPEDlaB55LyPFSMS+Ef2NlfUlgha+UQhwsxND6CEKqS5c0uG/se/2+4l0jXz+CTYBEh+USYB3gxcMKEo5XDFOGaM2Ncbc7FAKJIkYYN2DHmr4voSM5YkVibw5Lerw0kKdYyr0Xd0kmqTok3JLiLgQJBAOGZ1ao9oqWUzCKnpuTmXre8pZLmpWPhm6S1FU0vHjI0pZh/jusc8UXSRPnx1gLsgXq0ux30j968x/DmkESwxX8CQQCpY1+2p1aX2EzYO3UoTbBUTg7lCsopVNVf41xriek7XF1YyXOwEOSokp2SDQcRoKJ2PyPc2FJ/f54pigdsW0adAkAM8JTnydc9ZhZ7WmBhOrFuGnzoux/7ZaJWxSguoCg8OvbQk2hwJd3U4mWgbHWY/1XB4wHkivWBkhRpxd+6gOUjAkBH9qscS52zZzbGiwQsOk1Wk88qKdpXku4QDeUe3vmSuZwC85tNyu+KWrfM6/H74DYFbK/MzK7H8iz80uJye5jVAkAEqEB/LwlpXljFAxTID/SLZBb+bCIoV/kvg+2145F+CSSUjEWRhG/+OH0cQfqomfg36WrvHl0g/Xw06fg31HgK";

       PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decoder.decode(priKey));
       
       try{
    	   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	   privateKey = keyFactory.generatePrivate(priPKCS8);
    	   
       }catch (NoSuchAlgorithmException e) {
		// TODO: handle exception
    	   e.printStackTrace();
	} catch (InvalidKeySpecException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
        return privateKey;
    }
   

   public String RASEncrypt(String msg){
	   
      try{
    	  RSAPublicKey publicKey = (RSAPublicKey) getRasPublicKey();
          Cipher cipher = Cipher.getInstance("RSA");
    	  cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    	  String enmsg = encoder.encodeToString(cipher.doFinal(msg.getBytes()));
    	  
    	  return enmsg;
    }catch (NoSuchAlgorithmException e) {
    	  e.printStackTrace();
		// TODO: handle exception
	} catch (InvalidKeyException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NoSuchPaddingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalBlockSizeException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (BadPaddingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}catch (Exception e) {
		e.printStackTrace();
	}
	   return null;
   }
	
   public String RASDecrypt(String enmsg){
	   
	   RSAPrivateKey privateKey = (RSAPrivateKey) getRasPrivateKey();
		try{
	        Cipher cipher2 = Cipher.getInstance("RSA");
		    cipher2.init(Cipher.DECRYPT_MODE, privateKey);
		   
		    String demsg = new String(cipher2.doFinal(decoder.decode(enmsg)), "UTF-8");
		
		    return demsg;
		}catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   return null;
   }

	public static String MD5Encrypt(String str) {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
	  	} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexString.toString();
    }

	public static String sha1Encrypt(String str) {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexString.toString();
	}


}
